package netty.http.xml.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.net.InetAddress;
import java.util.List;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpUtil.setContentLength;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @program JavaBase
 * @description: 服务端编码器
 * @author: zhanglu
 * @create: 2021-10-28 11:44:00
 */
public class HttpServerXmlEncoder extends AbstractHttpXmlEncoder<HttpXmlResponse>{

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, HttpXmlResponse httpXmlResponse, List<Object> list) throws Exception {
        ByteBuf body = encode(httpXmlResponse);
        FullHttpResponse response = httpXmlResponse.getHttpResponse();
        if (response == null) {
            response = new DefaultFullHttpResponse(HTTP_1_1, OK, body);
//            HttpHeaders headers = response.headers();
//            headers.set(HttpHeaderNames.HOST, InetAddress.getLocalHost().getHostAddress());
//            headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
//            headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP.toString() + ',' + HttpHeaderValues.DEFLATE.toString());
//            headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
//            headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "zh");
//            headers.set(HttpHeaderNames.USER_AGENT, "Netty xml Http Client side");
//            headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        } else {
            response = new DefaultFullHttpResponse(response.protocolVersion(), response.status(), body);
        }
        response.headers().set(CONTENT_TYPE, "text/xml");
        setContentLength(response, body.readableBytes());
        list.add(response);
    }

}
